package com.mm.serivce.mp.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.domain.taxi.DMiniUserInfo;
import com.mm.domain.user.DLevelInfo;
import com.mm.mapper.taxi.DMiniUserInfoMapper;
import com.mm.mapper.user.DLevelInfoMapper;
import com.mm.serivce.mp.MiniUserInfoService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 小程序用户信息表 服务实现类
 * </p>
 *
 * @author JueDream
 * @since 2021-08-13
 */
@Service
public class MiniUserInfoServiceImpl extends ServiceImpl<DMiniUserInfoMapper, DMiniUserInfo> implements MiniUserInfoService {

    private final DMiniUserInfoMapper miniUserInfoMapper;

    private final DLevelInfoMapper levelInfoMapper;

    public MiniUserInfoServiceImpl(DMiniUserInfoMapper miniUserInfoMapper, DLevelInfoMapper levelInfoMapper) {
        this.miniUserInfoMapper = miniUserInfoMapper;
        this.levelInfoMapper = levelInfoMapper;
    }


    @Override
    public DMiniUserInfo queryMiniUserByOpenId(String openId) {
        DMiniUserInfo miniUserInfo = new DMiniUserInfo();
        LambdaQueryWrapper<DMiniUserInfo> queryWrapper = new LambdaQueryWrapper<DMiniUserInfo>();
        if (StrUtil.isNotBlank(openId)) {
            queryWrapper.eq(DMiniUserInfo::getOpenId, openId);
            queryWrapper.eq(DMiniUserInfo::getDelFlg, '0');
            miniUserInfo = miniUserInfoMapper.selectOne(queryWrapper);
            if (Objects.nonNull(miniUserInfo)) {
                if (Objects.nonNull(miniUserInfo.getMLevelId())) {
                    DLevelInfo levelInfo = levelInfoMapper.selectById(miniUserInfo.getMLevelId());
                    if (Objects.nonNull(levelInfo)) {
                        miniUserInfo.setMLeveName(levelInfo.getLevelName());
                    }
                }
            }
        }
        return miniUserInfo;
    }


    @Override
    public boolean updateMiniUser(DMiniUserInfo userInfo) {
        boolean flag = false;
        LambdaQueryWrapper<DMiniUserInfo> queryWrapper = new LambdaQueryWrapper<DMiniUserInfo>();
        // 验证openId 用户ID
        if (userInfo.getMId() != null && userInfo.getMId() > 0) {
            queryWrapper.eq(DMiniUserInfo::getMId, userInfo.getMId());
        }
        if (StrUtil.isNotBlank(userInfo.getOpenId())) {
            queryWrapper.eq(DMiniUserInfo::getOpenId, userInfo.getOpenId());
        }
        /**
         * isEmptyOfEntity 深层实体判断属性
         * isEmptyOfNormal 查询条件为空(不包含entity)
         * isEmptyOfWhere 查询条件为空(包含entity)
         */
        if (queryWrapper.nonEmptyOfNormal()) {
            int result = miniUserInfoMapper.update(userInfo, queryWrapper);
            if (result > 0) {
                flag = true;
            }
        }
        return flag;
    }

}
